package com.example.qqlogin;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.text.InputType;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.alibaba.fastjson2.JSONObject;
import com.hxc.basemodule.BaseActivity;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends BaseActivity {
    boolean isFirst = false;
    Drawable captchaImgDrawable;
    boolean isShowingPassword = false;
    EditText edPassword;
    EditText ediNumber;
    String uuid = "";
    String username = "";
    String pwd = "";
    String code = "";
    String token = "";
    String failMsg = "";
    boolean isLogin = false;
    String RuoYiBaseUrl = "http://1.117.75.13";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setImmersiveWindows();
        ImageView ivShowHidePassword = findViewById(R.id.iv);
        EditText editTextTextPassword2= findViewById(R.id.edPassword);
        isFirst = true;
        if(isFirst){
            login();
        }
        ivShowHidePassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!isShowingPassword){
                    //显示密码
                    editTextTextPassword2.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    ivShowHidePassword.setImageDrawable(getDrawable(R.mipmap.eyeso));
                }
                else{
                    editTextTextPassword2.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    ivShowHidePassword.setImageDrawable(getDrawable(R.mipmap.eyesc));
                }
                isShowingPassword=!isShowingPassword;
            }
        });
        edPassword = findViewById(R.id.edPassword);
        ediNumber = findViewById(R.id.edNumber);
    }
    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected int setCurrentLayoutId() {
        return R.layout.activity_main;
    }
    public void handleLogin() throws IOException {
        String url = String.format("%s:8080/login",RuoYiBaseUrl);
        OkHttpClient client = new OkHttpClient.Builder().connectTimeout(5000, TimeUnit.MILLISECONDS).build();
        JSONObject reqJson = new JSONObject();
        reqJson.put("code",code);
        reqJson.put("password",pwd);
        reqJson.put("username",username);
        reqJson.put("uuid",uuid);
        RequestBody requestBody = RequestBody.create(reqJson.toString().getBytes(StandardCharsets.UTF_8));
        Request request = new Request.Builder().url(url).
                addHeader("Content-Type","application/json;charset=UTF-8").
                addHeader("isToken","false").
                method("POST",requestBody).build();
        Response response = client.newCall(request).execute();
        JSONObject resJson = com.alibaba.fastjson2.JSONObject.parseObject(response.body().string());
        if (resJson.getInteger("code") == 200) {
            token = resJson.getString("token");
            failMsg = "success";
        } else {
            failMsg = resJson.getString("msg");
            throw new IOException(failMsg);
        }
    }
    public Bitmap getCaptchaImg() throws IOException {
        String url = String.format("%s:8080/captchaImage",RuoYiBaseUrl);
        OkHttpClient client = new OkHttpClient.Builder().connectTimeout(5000, TimeUnit.MILLISECONDS).build();
        Request request = new Request.Builder().url(url).build();
        Response response = client.newCall(request).execute();
        JSONObject jsonObject = com.alibaba.fastjson2.JSONObject.parseObject(response.body().string());
        if (response.isSuccessful() && jsonObject.getBoolean("captchaEnabled")) {
            this.uuid = jsonObject.getString("uuid");
            byte[] b  = jsonObject.getBytes("img");
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    class LoginThread implements Runnable {
        @Override
        public void run() {
            try {
                handleLogin();
            } catch (IOException e) {
                try {
                    finalize();
                } catch (Throwable ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    }

    class EndThread implements Runnable {
        @Override
        public void run() {
            try {
                Thread.sleep(3000000);
                finish();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    class GetCaptchaThread implements Runnable {
        @Override
        public void run() {
            try {
                captchaImgDrawable = new BitmapDrawable(getResources(),getCaptchaImg());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            while (!Thread.interrupted()){
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }
    }


    public void login() {
        isLogin = true;
        new Thread(new EndThread()).start();
        Thread thread = new Thread(new GetCaptchaThread());
        thread.start();
        EditText usrEd = findViewById(R.id.edNumber);
        EditText pwdEd = findViewById(R.id.edPassword);
        EditText captchaEd = findViewById(R.id.edVerificationCode);
        Button btnlogin = findViewById(R.id.btnlogin);
        while (captchaImgDrawable == null){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        ImageView captchaImg = findViewById(R.id.captchaImgView);
        captchaImg.setImageDrawable(captchaImgDrawable);
        captchaImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                thread.interrupt();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                Thread thread = new Thread(new GetCaptchaThread());
                thread.start();
                captchaImgDrawable = null;
                while (captchaImgDrawable == null){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                captchaImg.setImageDrawable(captchaImgDrawable);
            }
        });
        btnlogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                username = usrEd.getText().toString();
                pwd = pwdEd.getText().toString();
                code = captchaEd.getText().toString();
                if(!username.equals("") && !pwd.equals("")) {
                    new Thread(new LoginThread()).start();
                    failMsg = "";
                    while (failMsg == ""){
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    if (failMsg != "success"){
                        showAlertDialog("登录失败", failMsg, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                thread.interrupt();
                                try {
                                    Thread.sleep(100);
                                } catch (InterruptedException e) {
                                    throw new RuntimeException(e);
                                }
                                Thread thread = new Thread(new GetCaptchaThread());
                                thread.start();
                                captchaImgDrawable = null;
                                while (captchaImgDrawable == null){
                                    try {
                                        Thread.sleep(1000);
                                    } catch (InterruptedException e) {
                                        throw new RuntimeException(e);
                                    }
                                }
                                captchaImg.setImageDrawable(captchaImgDrawable);

                            }
                        });
                        isLogin = false;
                    }
                    else {
                        showAlertDialog("登录成功", token);
                        isLogin = true;
                    }
                }
                else{
                    Toast.makeText(MainActivity.this, "请输入用户名或密码", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (!isFirst){
            login();
        }
        else{
            isFirst = false;
        }
    }
    protected int  getStateBarHeight(){
        int result = 0;
        int resourceId = this.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = this.getResources().getDimensionPixelSize(resourceId);
        };
        return result;
    }

    /**
     * 设置沉浸式窗口
     */
    protected  void setImmersiveWindows(){
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
            View root = ((ViewGroup)findViewById(android.R.id.content)).getChildAt(0);
            root.setPadding(0,getStateBarHeight(),0,0);
        }
    }


}